/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dialog;

import main.Demo;
import dto.ApplicationAccessed;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableRowSorter;
import util.DateUtil;
import util.ModelTable;
import util.TableUtil;
import xml.XmlFile3;

/**
 *
 * @author phat10130059
 */
public class ShowHistory extends javax.swing.JPanel {

    /**
     * Creates new form ShowHistory
     */
    public String filePath = null;
    private ModelTable dmodel;
    private TableRowSorter<ModelTable> sorter;
    private JPanel plSearch;
    private JTextField txtSearch;
    private JButton btSearch;
    private List<ApplicationAccessed> list;
    private JTextField txtStart;
    private JTextField txtEnd;
    private JCheckBox cbSite;
    private JCheckBox cbApplication;
    private Demo demo;
    
    public ShowHistory(JDialog jdialog, Demo jframe) {
        
        this.demo = jframe;
        creatTable();
        
        initComponents();
        
        
        plSearch = new JPanel(new GridLayout(0, 10));
        
        if (demo.langPo) {
            plSearch.setBorder(BorderFactory.createTitledBorder(
                    null, "Informações de pesquisa", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
                    new java.awt.Font("Tahoma", 0, 12)));            
        } else {
            plSearch.setBorder(BorderFactory.createTitledBorder(
                    null, "Research information", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
                    new java.awt.Font("Tahoma", 0, 12)));            
        }
        
        
        
        
        txtSearch = new JTextField();
        txtSearch.setText("");
        
        txtSearch.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                txtSearchKeyPressed(e);
            }
        });
        
        
        plSearch.add(txtSearch);
        
        if (demo.langPo) {
            btSearch = new JButton("Pesquisar");
        } else {
            btSearch = new JButton("Search");
        }
        
        
        
        btSearch.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                btSearchAction(e);
            }
        });
        
        plSearch.add(btSearch);
        
        
        initDate();
        
        initCheckBox();
        
        
        this.add(plSearch, BorderLayout.NORTH);
        
        
        table.setRowHeight(40);
        
        filePath = jframe.filePath;
        
        initTable();
        
    }
    
    private void initDate() {
        
        JLabel jLabel = null;
        if (demo.langPo) {
            jLabel = new JLabel("Partir data:    ");
        } else {
            jLabel = new JLabel("From date:    ");
        }
        
        jLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        plSearch.add(jLabel);
        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        
        String startDate = simpleDateFormat.format(new Date());
        
        txtStart = new JTextField(startDate);
        txtStart.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                txtStartKeyPressed(e);
            }
        });
        
        
        plSearch.add(txtStart);
        
        
        JLabel jLabel2 = null;
        if (demo.langPo) {
            jLabel2 = new JLabel("Para data:    ");
        } else {
            jLabel2 = new JLabel("To date:    ");
        }
        jLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
        plSearch.add(jLabel2);
        
        
        
        String endDate = simpleDateFormat.format(new Date());
        
        txtEnd = new JTextField(endDate);
        txtEnd.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                txtEndKeyPressed(e);
            }
        });
        
        plSearch.add(txtEnd);
    }
    
    private void initCheckBox() {
        JLabel jLabel = new JLabel();
        plSearch.add(jLabel);
        
        
        
        if (demo.langPo) {
            cbSite = new JCheckBox("Site");
        } else {
            cbSite = new JCheckBox("Website");
        }
        
        cbSite.setSelected(true);
        cbSite.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                cbSiteMouseClicked(e);
            }
        });
        plSearch.add(cbSite);
        
        if (demo.langPo) {
            cbApplication = new JCheckBox("Aplicação");
        } else {
            cbApplication = new JCheckBox("Application");
        }
        cbApplication.setSelected(true);
        cbApplication.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                cbApplicationMouseClicked(e);
            }
        });
        
        plSearch.add(cbApplication);
        
    }
    
    private void btSearchAction(ActionEvent e) {
        searchInfo();
    }
    
    private void txtSearchKeyPressed(KeyEvent evt) {
        
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    searchInfo();
                }
            }).start();
        }
        
    }
    
    private void cbSiteMouseClicked(MouseEvent evt) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                searchInfo();
            }
        }).start();
        
    }
    
    private void cbApplicationMouseClicked(MouseEvent e) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                searchInfo();
            }
        }).start();
    }
    
    private void txtStartKeyPressed(KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    searchInfo();
                }
            }).start();
        }
    }
    
    private void txtEndKeyPressed(KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    searchInfo();
                }
            }).start();
        }
    }
    
    private void searchInfo() {
        TableUtil.clearTable(dmodel);
        
        String text = txtSearch.getText().trim().toLowerCase();
        
        for (ApplicationAccessed applicationAccessed : list) {
            
            boolean checkDate = DateUtil.checkDate(txtStart.getText(), txtEnd.getText(), applicationAccessed.getDate());
            
            if (applicationAccessed.getWindow().toLowerCase().contains(text) && (checkDate == true)) {
                try {
                    BufferedImage img = null;
                    img = ImageIO.read(new File(filePath + File.separator + applicationAccessed.getImage()));
                    Image scaledInstance = img.getScaledInstance(60,
                            40, Image.SCALE_SMOOTH);
                    
                    ImageIcon icon = new ImageIcon(scaledInstance);
                    icon.setDescription(applicationAccessed.getImage());
                    
                    if (applicationAccessed.getType().equals("appTile")) {
                        if (cbApplication.isSelected()) {
                            dmodel.insertRow(dmodel.getRowCount(), new Object[]{
                                        applicationAccessed.getId(),
                                        applicationAccessed.getDate() + "    " + applicationAccessed.getHours(),
                                        applicationAccessed.getUser(),
                                        icon,
                                        "<html>" + applicationAccessed.getWindow() + " | "
                                        + "<font color=\"blue\">" + applicationAccessed.getPathProcess() + "</font>"
                                    });
                        }
                        
                        
                        
                    } else {
                        if (cbSite.isSelected()) {
                            dmodel.insertRow(dmodel.getRowCount(), new Object[]{
                                        applicationAccessed.getId(),
                                        applicationAccessed.getDate() + "    " + applicationAccessed.getHours(),
                                        applicationAccessed.getUser(),
                                        icon,
                                        "<html>" + applicationAccessed.getWindow() + " | "
                                        + "<a href=" + applicationAccessed.getUrl() + ">" + applicationAccessed.getUrl() + "</a>"
                                    });
                        }
                        
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private void creatTable() {
        
        
        if (demo.langPo) {
            Object rows[][] = {};
            Object headers[] = {"Id", "Tempo", "Usuária", "Imagem", "Janela"};
            dmodel = new ModelTable(rows, headers);
            dmodel.setCanEdit(new boolean[]{false, false, false, false, false});
            dmodel.setTypes(new Class[]{String.class, String.class, String.class, ImageIcon.class, String.class});
        } else {
            Object rows[][] = {};
            Object headers[] = {"Id", "Time", "User", "Image", "Window"};
            dmodel = new ModelTable(rows, headers);
            dmodel.setCanEdit(new boolean[]{false, false, false, false, false});
            dmodel.setTypes(new Class[]{String.class, String.class, String.class, ImageIcon.class, String.class});
        }
        
        
    }
    
    private void initTable() {
        //khong cho column di chuyen
        table.getTableHeader().setReorderingAllowed(false);

        //set width column
        table.getColumn("Id").setMinWidth(0);
        table.getColumn("Id").setMaxWidth(0);
        table.getColumn("Id").setWidth(0);
        
        
        if (demo.langPo) {
            table.getColumn("Tempo").setMinWidth(120);
            table.getColumn("Tempo").setMaxWidth(120);
            table.getColumn("Tempo").setWidth(120);
            
            table.getColumn("Usuária").setMinWidth(120);
            table.getColumn("Usuária").setMaxWidth(200);
            table.getColumn("Usuária").setWidth(120);
            
            table.getColumn("Imagem").setMinWidth(60);
            table.getColumn("Imagem").setMaxWidth(60);
            table.getColumn("Imagem").setWidth(60);
        } else {
            table.getColumn("Time").setMinWidth(120);
            table.getColumn("Time").setMaxWidth(120);
            table.getColumn("Time").setWidth(120);
            
            table.getColumn("User").setMinWidth(120);
            table.getColumn("User").setMaxWidth(200);
            table.getColumn("User").setWidth(120);
            
            table.getColumn("Image").setMinWidth(60);
            table.getColumn("Image").setMaxWidth(60);
            table.getColumn("Image").setWidth(60);
        }
        
        
        
        
        
        table.setShowGrid(false);
        table.setIntercellSpacing(new Dimension(0, 0));

//        table1.setTableHeader(null);

        
        TableUtil.clearTable(dmodel);
        
        TableUtil.sortTable(dmodel, table, sorter);
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                searchAllTable();
            }
        }).start();
        
        
    }
    
    public void searchAllTable() {
        
        TableUtil.clearTable(dmodel);
        
        list = XmlFile3.readFileXml(filePath + File.separator + "fileHistory.xml");



        //        table.setValueAt(icon, row, column);

        for (ApplicationAccessed applicationAccessed : list) {
            
            if (DateUtil.checkDate(txtStart.getText(), txtEnd.getText(), applicationAccessed.getDate())) {
                BufferedImage img = null;
                try {
                    img = ImageIO.read(new File(filePath + File.separator + applicationAccessed.getImage()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
                Image scaledInstance = img.getScaledInstance(60,
                        40, Image.SCALE_SMOOTH);
                
                ImageIcon icon = new ImageIcon(scaledInstance);
                icon.setDescription(applicationAccessed.getImage());
                
                if (applicationAccessed.getType().equals("appTile")) {
                    if (cbApplication.isSelected()) {
                        dmodel.insertRow(dmodel.getRowCount(), new Object[]{
                                    applicationAccessed.getId(),
                                    applicationAccessed.getDate() + "    " + applicationAccessed.getHours(),
                                    applicationAccessed.getUser(),
                                    icon,
                                    "<html>" + applicationAccessed.getWindow() + " | "
                                    + "<font color=\"blue\">" + applicationAccessed.getPathProcess() + "</font>"
                                });
                    }
                    
                    
                    
                } else {
                    if (cbSite.isSelected()) {
                        dmodel.insertRow(dmodel.getRowCount(), new Object[]{
                                    applicationAccessed.getId(),
                                    applicationAccessed.getDate() + "    " + applicationAccessed.getHours(),
                                    applicationAccessed.getUser(),
                                    icon,
                                    "<html>" + applicationAccessed.getWindow() + " | "
                                    + "<a href=" + applicationAccessed.getUrl() + ">" + applicationAccessed.getUrl() + "</a>"
                                });
                    }
                    
                }
                
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        table.setModel(dmodel);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
        
        int r = table.getSelectedRow();
        int c = table.getSelectedColumn();
        
        if (r > -1) {
            
            if (c == 3) {
                ImageIcon image = (ImageIcon) table.getValueAt(r, 3);

//                System.out.println(image.getDescription());

                ShowImageDialog showImageDialog = new ShowImageDialog(image.getDescription(), filePath);
                showImageDialog.setVisible(true);
                
            }
        }
        
        
    }//GEN-LAST:event_tableMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
